<?php

namespace App\Jobs\Cruise;

use App\Models\Cruise\CruiseCheckAgainstModel;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckRectifyModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\Cruise\CruiseOrderProcessModel;
use App\Service\Cruise\Check\CruiseCheckAgainstService;
use App\Service\Cruise\Mission\CheckInputService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class RectifyExpire implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 1800;

    private int $cruiseOrderDetailId;

    /**
     * 整改单到期，自动生成违约函
     *
     * @return void
     */
    public function __construct(int $cruiseOrderDetailId)
    {
        $this->cruiseOrderDetailId = $cruiseOrderDetailId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info("RectifyExpire enter cruiseOrderDetailId:{$this->cruiseOrderDetailId}");

        // 巡检报告
        $orderDetail = CruiseCheckDetailModel::query()->with('cruiseOrderRel')->find($this->cruiseOrderDetailId);
        if (!$orderDetail) {
            $this->delete();
            return;
        }

        // 已关闭
        /*$closeCount = CruiseCheckRectifyModel::query()
            ->where('cruiseCheckDetailId', $this->cruiseOrderDetailId)
            ->where('status', CruiseCheckRectifyModel::STATUS_CLOSE)
            ->count();
        if ($closeCount) {
            $this->delete();
            return;
        }*/

        // 报告下 - 全量的整改单
        $rectifyModels      = CruiseCheckRectifyModel::query()
                                                     ->where('cruiseCheckDetailId', $this->cruiseOrderDetailId)
                                                     ->get();
        $rectifyModelsCount = $rectifyModels->count();

        // 已关闭
        $closeCount = $rectifyModels->where('status', CruiseCheckRectifyModel::STATUS_CLOSE)->count();
        if ($closeCount == $rectifyModelsCount) {
            $this->delete();
            return;
        }
        $rectifyModelsCount = $rectifyModelsCount - $closeCount;

        // 已整改
        $rectifyModelsDone      = $rectifyModels->where('status', CruiseCheckRectifyModel::STATUS_FINISH);
        $rectifyModelsDoneCount = $rectifyModelsDone->count();

        // 已超过60%的整改率
        if ($rectifyModelsCount > 0 && $rectifyModelsDoneCount / $rectifyModelsCount >= 0.6) {
            $this->delete();
            return;
        }

        // 取一个整改单拿到详情
        $rectifyModel = $rectifyModels->first();

        // 判断执行时间
        if ($rectifyModel->auditEndTime > time()) {
            $this->delay($rectifyModel->auditEndTime - time());
            return;
        }

        // 判断是否已生成过，整改单类型的违约函
        $repeatAgainst = CruiseCheckAgainstModel::query()
                                                ->where('cruiseCheckDetailId', $this->cruiseOrderDetailId)
                                                ->where('businessType', CruiseCheckAgainstModel::BUSINESS_TYPE_RECTIFY)
                                                ->where('createdByUid', 0) // 仅判断 - 系统自动生成
                                                ->count();
        if ($repeatAgainst) {
            $this->delete();
            return;
        }

        // 生成超时违约函
        $shopId       = $rectifyModel->shopId;
        Log::info("RectifyExpire doing cruiseOrderDetailId:{$this->cruiseOrderDetailId} shopId: {$shopId}");

        $behaviorDesc = '';//违约行为描述
        $rectifyPlan  = '';//整改措施
        $behaviorDescCount = $rectifyPlanCount = 1;//序号
        $rectifyModels->where('status', CruiseCheckRectifyModel::STATUS_WAIT_SUBMIT)// 未整改
        ->each(function ($item) use (&$behaviorDesc, &$rectifyPlan, &$behaviorDescCount, &$rectifyPlanCount) {
                    $project = (new CheckInputService($item->cruiseOrderId, $item->createdByUid))
                        ->getProject($item->field);
                    if ($project) {
                        $reason = $project['customAttributes']['auditValue']['reason'] ?? "";
                        if ($reason) {
                            $rectifyPlan .= $rectifyPlanCount . "." . $reason . '\n';//追加换行符
                            $rectifyPlanCount++;
                        }
                        $text = $project['customAttributes']['auditValue']['desc'] ?? "";
                        if ($text) {
                            $behaviorDesc .= $behaviorDescCount . "." . $text . '\n';//追加换行符
                            $behaviorDescCount++;
                        }
                    }
                }
            );
        if ($behaviorDesc) {
            $behaviorDesc = substr($behaviorDesc, 0, -2);//去除最后一个换行符
        }
        if ($rectifyPlan) {
            $rectifyPlan = substr($rectifyPlan, 0, -2);//去除最后一个换行符
        }

        if ($orderDetail->templateType == CruiseTemplateModel::TYPE_3) {

            $createdAt = CruiseOrderProcessModel::query()
                                                ->where('cruiseOrderId', $orderDetail->orderId)
                                                ->where('step', CruiseOrderProcessModel::PROCESS_SUBMITTED)
                                                ->orderByDesc('id')
                                                ->value('createdAt');//流程任务提交日期
            // 审核到期后，未超过60%已整改率，生成超时违约函-此时违约函产生时间为提交巡检日期
            CruiseCheckAgainstService::addCheckAgainst(
                $shopId, CruiseCheckAgainstModel::DEFAULT_TIMEOUT_PRICE, CruiseCheckAgainstModel::LEVEL_PUNISH, '1,2',
                $this->cruiseOrderDetailId,
                CruiseCheckAgainstModel::BUSINESS_TYPE_RECTIFY, $this->cruiseOrderDetailId, $behaviorDesc, $rectifyPlan,
                CruiseCheckAgainstModel::TEMPLATE_TYPE_TIMEOUT
                , strtotime($createdAt)
            );
        }

        Log::info("RectifyExpire end cruiseOrderDetailId:{$this->cruiseOrderDetailId} shopId: {$shopId}");
    }
}
